package com.boot.mall.seckill.scheduled;

import com.boot.common.constant.SecKillConstant;
import com.boot.mall.seckill.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * 秒杀商品的定时上架
 *
 */
@Component
@Slf4j
public class SeckillSkuScheduled {

    @Autowired
    private SecKillService secKillService;
    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "*/20 * * * * ?")
    public void UpSecKillSkuScheduled(){
        // 获取分布式锁
        RLock lock = redissonClient.getLock(SecKillConstant.SEC_UP_LOCK);
        // 上锁5秒之后自动释放
        lock.lock(5, TimeUnit.SECONDS);
        try {
            secKillService.UpSecKillSkuScheduled();
            System.out.println("秒杀商品已缓存...");
        }finally {
            // 解锁
            lock.unlock();
        }
    }
}
